package com.resou.reader.reader.manager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.gson.Gson;
import com.resou.reader.ACache;
import com.resou.reader.R;
import com.resou.reader.api.entry.BookContentBean;
import com.resou.reader.api.entry.BookDetailBean;
import com.resou.reader.api.entry.ChapterItemBean;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.LoginResult;
import com.resou.reader.api.entry.Result;
import com.resou.reader.bookshelf.readhistory.datasupport.BookCollection;
import com.resou.reader.bookshelf.readhistory.datasupport.DataSupport;
import com.resou.reader.bookshelf.readhistory.datasupport.ReaderHistory;
import com.resou.reader.data.readhistory.ReadHistoryRepository;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.listener.LoginListener;
import com.resou.reader.mine.login.LoginFragment;
import com.resou.reader.mine.vipcenter.vipCenter.VipCenter;
import com.resou.reader.reader.OnAdViewLoadListener;
import com.resou.reader.reader.end.EndBookActivity;
import com.resou.reader.reader.m.ShowChar;
import com.resou.reader.reader.m.ShowLine;
import com.resou.reader.reader.p.ReaderPresenter;
import com.resou.reader.reader.utils.ScreenUtils;
import com.resou.reader.reader.utils.SpUtils;
import com.resou.reader.reader.utils.ViewUtils;
import com.resou.reader.reader.view.BookUnShelfView;
import com.resou.reader.reader.view.NativeTTAdView;
import com.resou.reader.reader.view.NoNetworkView;
import com.resou.reader.reader.view.PageView;
import com.resou.reader.reader.view.PayChapterView;
import com.resou.reader.utils.AppExecutors;
import com.resou.reader.utils.DateUtils;
import com.resou.reader.utils.EncryptUtils;
import com.resou.reader.utils.ErrorUtils;
import com.resou.reader.utils.NetworkUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.ReaderUtil;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.UIHelper;
import com.resou.reader.utils.UserUtil;
import com.resou.reader.utils.eventbus.LoadBookEvent;
import com.resou.reader.utils.log.DLog;
import com.resou.reader.utils.log.RsLog;
import com.resou.reader.view.Loading;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by ${Garrett} on 2018/9/11.
 * Contact me krouky@outlook.com
 */
public class PageFactory {

    private static final String TAG = "调试.PageFactory";

    private int mPageIndex;//当前页
    private int mPageSum;//总页数
    private int mLinesNumInPage;//一页能展示多少行
    private float mTextPadding = 0;
    private float mTextHeight;//文字高度
    private int mLineNumInFirstPage;//


    private int mChapterIndex;//章节索引
    private int mCharIndex;//本章中行索引
    private int mChapterSum;

    // *********************设置默认值start********************
    private float defaultLineSpace = 20;//默认行间距

    //********************外部可设置成员start**********************
    private int mTextSize = 55;//默认文字大小
    private int mTextColor = Color.BLACK;//默认文字颜色;
    private float mLineSpace = defaultLineSpace;//行间距
    private float textPadding = 0;//20;

    private int mWidth;
    private int mHeight;

    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Paint mChapterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private Paint mTitlePaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    private List<ChapterItemBean> mChapterList;//章节数据
    private List<ShowLine> mShowLines;//一章中所有行数据集
    private int mTopArea;//顶部预留 画章节名称
    private int mBottomArea;//底部预留 画电量、时间等
    private int mUsableAreaHeight;//画文字可利用的空间高度
    private int mPaddingLeft;//左边预留空白
    private int mPaddingRight; //右边预留空白

    //    private DecimalFormat decimalFormat = new DecimalFormat("#0.00");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
    private ReaderPresenter mReaderPresenter;
    private BookContentBean mBookContentBean;

    String isVipTAG = "0";
    String isPayTAG = "0";
    //历史和收藏
    private BookCollection mBookCollection;
    private ReaderHistory mReaderHistory;

    //付费
    private Rect des = new Rect();
    private Bitmap mPayBitmap;
    private PayChapterView mPayView;

    private Context mContext;
    private Rect rect;

    /**
     * 广告
     */
    private static Bitmap advertBitmap;
    private NativeTTAdView nativeTTAdView;
    public int adCount = 1001;
    private int mNativeAdvertHeight;
    private float adViewY = 0.0f;
    private boolean pageState = false;  //翻页状态 true标识下一页 ，false标识上一页
    private boolean isPreShow;
    private boolean isNextShow;

    /**
     * 下架视图
     */
    private static Bitmap unshelfBitmap;
    private BookUnShelfView bookUnShelfView;
    private boolean isUnShelf = false;//true 已经下架 false 未下架
    int mbookUnShelfViewHeight = 0;
    int bookViewHeight = 0;

    /**
     * 无网络
     */
    private static Bitmap mNoNetworkBitmap;
    private NoNetworkView mNoNetworkView;
    int mNoNetworkViewHeight = 0;
    int mNoNetworkViewY = 0;

    public PageFactory(Context mContext, ReaderPresenter readerPresenter, int chapterIndex, int pageIndex, int charIndex, String bookId, int chapterSum, boolean toNewChapter) {
        if (this.mContext == null) {
            this.mContext = mContext;
            init();
        }
        this.mChapterIndex = chapterIndex;
        this.mPageIndex = pageIndex;
        this.mCharIndex = charIndex;
        this.mChapterSum = chapterSum;
//        mChapterSum = 1000;
        if (mReaderPresenter == null) {
            mReaderPresenter = readerPresenter;
        }
        queryHistoryAndCollection(bookId);
        if (toNewChapter) {
            mBookContentBean = mReaderPresenter.getChapterContent2(mChapterSum - 1);
        } else {
            mBookContentBean = mReaderPresenter.getChapterContent2(mChapterIndex);
        }

        if (mBookContentBean != null) {
            mChapterName = mBookContentBean.getChapterName();
        }
        if (mTopArea == 0 || mBottomArea == 0 || mPaddingLeft == 0 || mPaddingRight == 0 || mWidth == 0 || mHeight == 0 || rect == null) {
            mTopArea = UIHelper.dip2px(mContext, 40);//顶部预留 画章节名称
            mBottomArea = UIHelper.dip2px(mContext, 30);//底部预留 画电量、时间等
            mPaddingLeft = UIHelper.dip2px(mContext, 20);//左边预留空白
            mPaddingRight = UIHelper.dip2px(mContext, 20); //右边预留空白
            Point size = new Point();
            ScreenUtils.getScreenSize(size);
            mWidth = (size.x > 0) ? size.x : ScreenUtils.getScreenWidth();
            mHeight = (size.y > 0) ? size.y : ScreenUtils.getScreenWidth(mContext);
            rect = new Rect(0, 0, mWidth, mHeight);
        }

        Log.i("高度---", "PageFactory: " + mHeight);
        if (mBookPageBg == null) {
            mBookPageBg = decodeBitmapResource(R.mipmap.read_bg_npz);
//            mBookPageBg = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.read_bg_npz);
        }
    }

    /**
     * 创建广告视图
     *
     * @param nativeTTAdView
     */
    public void createAdView(NativeTTAdView nativeTTAdView) {
        this.nativeTTAdView = nativeTTAdView;

        nativeTTAdView.setListener(new OnAdViewLoadListener() {
            @Override
            public void onAdViewLoadListener() {
                if (advertBitmap != null && !advertBitmap.isRecycled()) {
                    advertBitmap.recycle();
                    advertBitmap = null;
                }
                mNativeAdvertHeight = nativeTTAdView.getMeasuredHeight();
                adViewY = (mHeight - mNativeAdvertHeight) / 2;
                nativeTTAdView.setX(0);
                nativeTTAdView.setY(adViewY);
                advertBitmap = getViewBitmap2(nativeTTAdView, mWidth, mHeight, Color.TRANSPARENT);
            }

            @Override
            public void onShare() {
                if (NetworkUtils.isNetworkConnected(mContext)) {
                    mReaderPresenter.share(true);
                } else {
                    ToastUtil.makeShortToast("网络异常");
                }
            }

            @Override
            public void onMonthlyVip() {
                VipCenter.start(mContext);
            }

        });

    }

    /**
     * 创建下架视图视图
     *
     * @param unShelfView
     */
    public void createUnShelfView(BookUnShelfView unShelfView) {
        bookUnShelfView = unShelfView;
        if (unshelfBitmap != null && !unshelfBitmap.isRecycled()) {
            unshelfBitmap.recycle();
            unshelfBitmap = null;
        }
        mbookUnShelfViewHeight = unShelfView.getMeasuredHeight();
        bookViewHeight = (mHeight - unShelfView.getUnshelfHeight()) / 3;
        bookUnShelfView.setX(mWidth);
        bookUnShelfView.setY(bookViewHeight);
        unshelfBitmap = getViewBitmap2(bookUnShelfView, mWidth, mHeight, Color.TRANSPARENT);
    }

    /**
     * 创建无网络视图
     *
     * @param noNetworkView
     */
    public void createNoNetworkView(NoNetworkView noNetworkView) {
        mNoNetworkView = noNetworkView;
        if (mNoNetworkBitmap != null && !mNoNetworkBitmap.isRecycled()) {
            mNoNetworkBitmap.recycle();
            mNoNetworkBitmap = null;
        }
        mNoNetworkViewHeight = noNetworkView.getMeasuredHeight();
        mNoNetworkViewY = (mHeight - noNetworkView.getNoNetworkHeight()) / 3;
        mNoNetworkView.setX(mWidth);
        mNoNetworkView.setY(bookViewHeight);
        mNoNetworkBitmap = getViewBitmap2(mNoNetworkView, mWidth, mHeight, Color.TRANSPARENT);
    }


    /**
     * 标记为是否显示广告/每三页显示
     *
     * @return
     */
    public boolean isShowView() {
//        return PreferenceUtil.getInstance(mContext).getAdValue(getPresenter().getBookId()) % 5 == 0 ? true : false;
        Log.i(TAG, "isShowView: " + adCount);
        return adCount % 5 == 0 ? true : false;
    }


    /**
     * true标识  下一页 false标识 上一页；
     *
     * @return
     */
    public boolean isNexPage() {
        return this.pageState;
    }

    /**
     * 是否时广告页上一页
     */
    public boolean isAdPrePage() {
        return adCount % 5 == 3 ? true : false;
    }

    public void setChapterIndex(int chapterIndex) {
        this.mChapterIndex = chapterIndex;
    }

    public void setChapterSum(int mChapterSum) {
        this.mChapterSum = mChapterSum;
    }

    private void init() {
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(mTextColor);

        mTitlePaint.setColor(mContext.getResources().getColor(R.color.color_666));
        mTitlePaint.setTextSize(UIHelper.sp2px(mContext, 12));

        mChapterPaint.setTextSize(mTextSize * 1.4f);
        mChapterPaint.setColor(mTextColor);

        Paint.FontMetrics fm = mPaint.getFontMetrics();
        mTextHeight = fm.bottom - fm.top;
        convertBatteryBitmap();
    }

    /**
     * 设置画布大小
     *
     * @param width  布局宽度
     * @param height 布局高度
     */
    public void setCanvasArea(int width, int height) {
        this.mWidth = width;
        mBigChapterFM = mChapterPaint.getFontMetrics();
        if (mBookContentBean == null) {
            Log.i(TAG, "setCanvasArea:mBookContent = null ");
            return;
        }
        String content = "";
        content = getDrawBookContent(content);
        int payBitmapHeight = 0;
        if (!NetworkUtils.isNetworkConnected(mContext)) {
            if (mNoNetworkBitmap != null && !mNoNetworkBitmap.isRecycled()) {
                mNoNetworkBitmap.recycle();
                mNoNetworkBitmap = null;
            }
            initNoNetwork();
        }
        if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay()) && !isSubSidyState()) {
            if (mPayBitmap != null) {
                mPayBitmap.recycle();
                mPayBitmap = null;
            }
            initPayView();
            payBitmapHeight = UIHelper.dip2px(mContext, 399);
        }
        if (1 == mBookContentBean.getUnshelf()) {
            if (unshelfBitmap != null) {
                unshelfBitmap.recycle();
                unshelfBitmap = null;
            }
            initUnShelf();
        }
        mShowLines = ReaderUtil.breakToLineList(content, mWidth - mPaddingLeft - mPaddingRight, textPadding, mPaint);

        mUsableAreaHeight = mHeight - mTopArea - mBottomArea - payBitmapHeight;
        mLinesNumInPage = ReaderUtil.measureLines(mUsableAreaHeight, mLineSpace, mPaint);

        //如果是第0页 需要画章节大标题;
        mBigChapterLines = ReaderUtil.breakToLineList(mChapterName, mWidth - mPaddingLeft - mPaddingRight, 0, mChapterPaint);
        float chapterTitleNumHeight = mBigChapterLines.size() * (mBigChapterFM.bottom - mBigChapterFM.top + mLineSpace) * 1.5f;//大标题占总高度
        //第0页内容行数
        mLineNumInFirstPage = ReaderUtil.measureLines(mUsableAreaHeight - chapterTitleNumHeight, mLineSpace, mPaint);
        mPageSum = mShowLines.size() - mLineNumInFirstPage == 0 ? 1 : ((mShowLines.size() - mLineNumInFirstPage) - 1) / Math.max(1, mLinesNumInPage) + 1 + 1;

//        DLog.d(TAG, mChapterName + "  ,正文总行数：" + mShowLines.size() + "  ,第一页行数:" + mLineNumInFirstPage + "  ,总页数: " + mPageSum);
//        for (int i = 0; i < mShowLines.size(); i++) {
//            ShowLine showLine = mShowLines.get(i);
//            DLog.d(TAG, "showLines 第" + i + "行 ::::" + showLine.getLineData());
//        }

        mPageIndex = Math.min(mPageIndex, mPageSum - 1);
    }

    private String getDrawBookContent(String content) {
        if (mBookContentBean.getZsChapterLink() == null)//从追书获取
        {
            try {
                content = EncryptUtils.decrypt(mBookContentBean.getContent(), mReaderPresenter.getBookId(), mBookContentBean.getChapterId());
                if (!content.startsWith("　　")) {
                    content = "　　" + content;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            content = mBookContentBean.getContent();
        }
        return content;
    }

    private Paint.FontMetrics mBigChapterFM;
    private String mChapterName = "";
    private List<ShowLine> mBigChapterLines;
    private int mBgColor = 0xFFF7F3EF;

    public void setPayView(PayChapterView view) {
        this.mPayView = view;
    }

    /**
     * 在阅读器上
     */
    boolean isStartAuto = false;

    public void initPayView() {
        if (mBookContentBean == null)
            return;
        if (mPayBitmap != null && !mPayBitmap.isRecycled()) {
            mPayBitmap.recycle();
            mPayBitmap = null;
        }

        int balance = 0;
        int giftBalance = 0;
        balance = (int) UserInstance.getLoginData().getBlance();
        giftBalance = (int) UserInstance.getLoginData().getGiftBlance();
        mPayView.setBlance(balance, giftBalance);

        //        //能量值的显示
        LoginData loginData = UserInstance.getLoginData();
        Integer energy = Integer.valueOf(loginData.getEnergy());
        mPayView.setPayText("自己买单");

        /**
         * getIsVipUser==1会员 否则非会员
         */
        if ("1".equals(mBookContentBean.getIsVipUser())) {
            mPayView.getChapterVipSubMonthly().setVisibility(View.GONE);
            mPayView.setPayYPrice(" " + mBookContentBean.getPrice() + "热币 ");
            mPayView.setPayPrice(" " + mBookContentBean.getVipPrice() + "热币 ");
            mPayView.setRealPayPrice(" " + mBookContentBean.getVipPrice() + "热币  ");
            mPayView.setYDes(mBookContentBean.getVipDiscount() + "");
            /**
             * 判断是否是需要全本购买
             */
            if (mBookContentBean != null && mBookContentBean.getChargeType() == 2) {
                mPayView.setAllBookPay(true);
                if (Integer.valueOf(mBookContentBean.getIsVipUser()) > (balance + giftBalance + energy)) {
                    mPayView.setPayText("余额不足，充值并购买");
//                mPayView.setAutoPay(mReaderPresenter.isAutoBuy());
                } else {
                    mPayView.setPayText("全本购买");
                }
            } else {
                mPayView.setAllBookPay(false);
                if (energy <= 15) {
                    //用户能量值大于15
                    if (Integer.valueOf(mBookContentBean.getVipPrice()) <= energy) {
                        //内容价格小于等于用户能量值
                        //显示内容价格
                        mPayView.setRealPayDes("能量抵扣" + Integer.valueOf(mBookContentBean.getVipPrice()) + "热币>>");
                        mPayView.setRealPayPrice("0热币");
                        mPayView.setPayText("自己买单");
                    } else {
                        //内容价格大于用户能量值
                        //显示用户的能量值
                        mPayView.setRealPayDes("能量抵扣" + energy + "热币>>");
                        //显示用户的应该支付的实际价格
                        int actualPay = Integer.valueOf(mBookContentBean.getVipPrice()) - energy;
                        actualPay = actualPay < 0 ? 0 : actualPay;
                        if (actualPay > (balance + giftBalance + energy)) {
                            mPayView.setPayText("余额不足，充值并购买");
                        } else {
                            mPayView.setPayText("自己买单");
                        }
                        mPayView.setRealPayPrice(actualPay + "热币");
                    }
                } else {
                    mPayView.setPayText("自己买单");
                    //用户能量值大于15时
                    //实际抵扣15
                    if (Integer.valueOf(mBookContentBean.getVipPrice()) < 15) {
                        mPayView.setRealPayDes("能量抵扣" + Integer.valueOf(mBookContentBean.getVipPrice()) + "热币>>");
                    } else {
                        mPayView.setRealPayDes("能量抵扣15热币>>");
                    }
                    int actualPay = Integer.valueOf(mBookContentBean.getVipPrice()) - 15;
                    actualPay = actualPay < 0 ? 0 : actualPay;
                    mPayView.setRealPayPrice(actualPay + "热币");
                }
            }
        } else {
            /**
             * 非会员
             */
            mPayView.getPayYPriceView().setVisibility(View.GONE);
            mPayView.setPayPrice(mBookContentBean.getPrice() + "热币 ");
            mPayView.setRealPayPrice(mBookContentBean.getPrice() + "热币 ");
            mPayView.setYDes("");
            /**
             * 判断是否是需要全本购买
             */
            if (mBookContentBean != null && mBookContentBean.getChargeType() == 2) {
                mPayView.setAllBookPay(true);
                if (mBookContentBean.getPrice() > (balance + giftBalance + energy)) {
                    mPayView.setPayText("余额不足，充值并购买");
//                mPayView.setAutoPay(mReaderPresenter.isAutoBuy());
                } else {
                    mPayView.setPayText("全本购买");
                }
            } else {
                mPayView.setAllBookPay(false);
                if (energy <= 15) {
                    //用户能量值大于15
                    if (mBookContentBean.getPrice() <= energy) {
                        //内容价格小于等于用户能量值
                        //显示内容价格
                        mPayView.setRealPayDes("能量抵扣" + mBookContentBean.getPrice() + "热币>>");
                        mPayView.setRealPayPrice("0热币");
                        mPayView.setPayText("自己买单");
                    } else {
                        //内容价格大于用户能量值
                        //显示用户的能量值
                        mPayView.setRealPayDes("能量抵扣" + energy + "热币>>");
                        //显示用户的应该支付的实际价格
                        int actualPay = mBookContentBean.getPrice() - energy;
                        actualPay = actualPay < 0 ? 0 : actualPay;
                        if (actualPay > (balance + giftBalance + energy)) {
                            mPayView.setPayText("余额不足，充值并购买");
//                        mPayView.setAutoPay(mReaderPresenter.isAutoBuy());
                        } else {
                            mPayView.setPayText("自己买单");
                        }
                        mPayView.setRealPayPrice(actualPay + "热币");
                    }
                } else {
                    mPayView.setPayText("自己买单");
                    //用户能量值大于15时
                    //实际抵扣15
                    if (mBookContentBean.getPrice() < 15) {
                        mPayView.setRealPayDes("能量抵扣" + mBookContentBean.getPrice() + "热币>>");
                    } else {
                        mPayView.setRealPayDes("能量抵扣15热币>>");
                    }
                    //支付多出的价格
                    int actualPay = mBookContentBean.getPrice() - 15;
                    actualPay = actualPay < 0 ? 0 : actualPay;
                    mPayView.setRealPayPrice(actualPay + "热币");
                }
            }
        }

        if (SpUtils.getTheme(mContext)) {
            mPayView.setTextColor(mContext.getResources().getColor(R.color.color_666));
        } else {
            mPayView.setTextColor(mContext.getResources().getColor(R.color.color_333));
        }
        mPayView.setAutoPay(isStartAuto);
        try {
            mPayBitmap = getViewBitmap2(mPayView, mWidth, mHeight, Color.TRANSPARENT);
        } catch (OutOfMemoryError e) {
            Log.i(TAG, "initPayView: " + e.getMessage());
        }
    }


    /**
     * 是否下架
     *
     * @return
     */
    public boolean isUnShelf() {
        return isUnShelf;
    }

    /**
     * 设置是否下架
     *
     * @param unShelf
     */
    public void setUnShelf(boolean unShelf) {
        isUnShelf = unShelf;
    }

    /**
     * 刷新下架视图
     */
    private void initUnShelf() {
//        if (mBookContentBean == null) {
//            return;
//        }
        if (unshelfBitmap != null && !unshelfBitmap.isRecycled()) {
            unshelfBitmap.recycle();
            unshelfBitmap = null;
        }
        try {
            if (SpUtils.getTheme(mContext)) {
                bookUnShelfView.setIcon(R.mipmap.ic_unshelficon_dark);
                bookUnShelfView.setTextColor(R.color.color_666);
            } else {
                bookUnShelfView.setIcon(R.mipmap.ic_unshelficon_light);
                bookUnShelfView.setTextColor(R.color.color_333);
            }
            unshelfBitmap = getViewBitmap2(bookUnShelfView, mWidth, mHeight, Color.TRANSPARENT);
        } catch (Exception e) {
            Log.i(TAG, "initUnShelf: " + e.getMessage());
        }
    }

    /**
     * 刷新无网络
     */
    private void initNoNetwork() {
        if (mNoNetworkBitmap != null && !mNoNetworkBitmap.isRecycled()) {
            mNoNetworkBitmap.recycle();
            mNoNetworkBitmap = null;
        }
        try {
            if (SpUtils.getTheme(mContext)) {
//                mNoNetworkView.setIcon(R.mipmap.ic_meiwang);
            } else {
                mNoNetworkView.setIcon(R.mipmap.ic_meiwang);
            }
            mNoNetworkBitmap = getViewBitmap2(mNoNetworkView, mWidth, mHeight, Color.TRANSPARENT);
        } catch (Exception e) {
            Log.i(TAG, "initUnShelf: " + e.getMessage());
        }
    }

    //是否点击了购买
    public boolean isClickedPay(MotionEvent ev) {
        if (isUnShelf) {
            return false;
        }
        boolean result = false;
        if (mBookContentBean != null) {
            RectF rect = new RectF(des.left + mPayView.getChapterPay().getLeft() + 100, des.top + mPayView.getChapterPay().getTop(), des.left + mPayView.getChapterPay().getLeft() + mPayView.getChapterPay().getWidth() + 100, des.top + mPayView.getChapterPay().getTop() + mPayView.getChapterPay().getHeight());
            if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay()) && rect.contains(ev.getX(), ev.getY())) {
                result = true;
            }
        }
        return result;
    }

    //选择自动购买下一章按钮
    public boolean selectAutoBuy(MotionEvent ev) {
        if (mPayView.isAllBookPay() || isUnShelf) {
            return false;
        }
        boolean result = false;
        if (mBookContentBean != null) {
            RectF rect = new RectF(des.left + mPayView.getChapterAutoPay().getLeft(), des.top + mPayView.getChapterAutoPay().getTop(), des.right - mPayView.getChapterAutoPay().getRight(), des.top + mPayView.getChapterAutoPay().getTop() + mPayView.getChapterAutoPay().getHeight());
            if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay()) && rect.contains(ev.getX(), ev.getY())) {
                result = true;
            }
        }
        return result;
    }

    //点击了批量购买
    public boolean isClickedBatchPay(MotionEvent ev) {
        if (mPayView.isAllBookPay() || isUnShelf) {
            return false;
        }
        boolean result = false;
        if (mBookContentBean != null) {
            RectF rect = new RectF(des.left + mPayView.getChapterMoreBook().getLeft(), des.top + mPayView.getChapterMoreBook().getTop(), mPayView.getChapterMoreBook().getLeft() + mPayView.getChapterMoreBook().getWidth() + 100, des.top + mPayView.getChapterMoreBook().getTop() + mPayView.getChapterMoreBook().getHeight());
            if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay()) && rect.contains(ev.getX(), ev.getY())) {
                result = true;
            }
        }
        return result;
    }

    //开通Vip包月
    public boolean isClickedVipPay(MotionEvent ev) {
        if ("1".equals(UserInstance.getLoginData().getIsVipUser()) || mPayView.getChapterVipSubMonthly().getVisibility() == View.GONE || isUnShelf) {
            return false;
        }
        boolean result = false;
        if (mBookContentBean != null) {
            RectF rect = new RectF(des.left + mPayView.getChapterVipSubMonthly().getLeft() + 50, des.top + mPayView.getChapterVipSubMonthly().getTop() - 20, des.left + mPayView.getChapterVipSubMonthly().getLeft() + mPayView.getChapterVipSubMonthly().getWidth() + 100, des.top + mPayView.getChapterVipSubMonthly().getTop() + mPayView.getChapterVipSubMonthly().getHeight() + 20);
            if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay()) && rect.contains(ev.getX(), ev.getY())) {
                result = true;
            }
        }
        return result;
    }

    /***
     * 点击热搜为我支付按钮
     * @param ev
     * @return
     */
    public boolean isClickedResouForMePay(MotionEvent ev) {
        if ("1".equals(UserInstance.getLoginData().getIsVipUser()) || isUnShelf) {
            return false;
        }
        boolean result = false;
        if (mBookContentBean != null) {
            RectF rect = new RectF(des.left + mPayView.getChapterResouForMePay().getLeft() + 50, des.top + mPayView.getChapterResouForMePay().getTop() - 20, des.left + mPayView.getChapterResouForMePay().getLeft() + mPayView.getChapterResouForMePay().getWidth() + 50, des.top + mPayView.getChapterResouForMePay().getTop() + mPayView.getChapterResouForMePay().getHeight() + 20);
            if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay()) && rect.contains(ev.getX(), ev.getY())) {
                result = true;
            }
        }
        return result;
    }


    //点击了能量抵扣的小箭头及其文字
    public boolean isClickedEnergyDeduction(MotionEvent ev) {
//        if (mPayView.isAllBookPay()) {
//            return false;
//        }
//        boolean result = false;
//        if (mBookContentBean != null) {
//            RectF rect = new RectF(des.left + mPayView.getChapterActive().getLeft() + 100, des.top + mPayView.getChapterActive().getTop(), des.right - mPayView.getChapterActive().getRight() + 250, des.top + mPayView.getChapterActive().getTop() + mPayView.getChapterActive().getHeight());
//            if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay()) && rect.contains(ev.getX(), ev.getY())) {
//                result = true;
//            }
//        }
        return false;
    }

    //是否点击刷新下架书籍
    public boolean refreshUnshelfData(MotionEvent ev) {
        boolean result = false;
        if (isUnShelf && NetworkUtils.isNetworkConnected(mContext)) {
            RectF rect = new RectF(bookUnShelfView.getRetry().getLeft(), bookViewHeight + bookUnShelfView.getRetry().getTop(), bookUnShelfView.getRetry().getLeft() + bookUnShelfView.getRetry().getWidth(), bookViewHeight + bookUnShelfView.getRetry().getTop() + bookUnShelfView.getRetry().getHeight());
            if (rect.contains(ev.getX(), ev.getY())) {
                result = true;
            }
        }
        return result;
    }

    //无网络情况是否点击刷新当前章节
    public boolean refreshNoNetworkfView(MotionEvent ev) {
        boolean result = false;
        if (mBookContentBean == null) {
            RectF rect = new RectF(mNoNetworkView.getRetry().getLeft(), mNoNetworkViewY + mNoNetworkView.getRetry().getTop(), mNoNetworkView.getRetry().getLeft() + mNoNetworkView.getRetry().getWidth(), mNoNetworkViewY + mNoNetworkView.getRetry().getTop() + mNoNetworkView.getRetry().getHeight());
            if (rect.contains(ev.getX(), ev.getY())) {
                result = true;
            }
        }
        return result;
    }

    private Bitmap mBookPageBg = null;

    public void onDraw(Canvas canvas) {
        Log.i("RealAnimation", "onDraw: 渲染");
        if (canvas == null) {
            return;
        }
        //清空画布
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        if (SpUtils.getBgIndex(mContext) == 4) {
            if (!SpUtils.getTheme(mContext)) {
                if (mBookPageBg != null && !mBookPageBg.isRecycled()) {
                    canvas.drawBitmap(mBookPageBg, null, rect, null);
                }
            } else {
                if (mBgColor != -1) {
                    canvas.drawColor(mBgColor);
                }
            }
        } else {
            if (mBgColor != -1) {
                canvas.drawColor(mBgColor);
            }
        }
        if (SpUtils.getProtectEye(mContext)) {
            canvas.drawColor(mContext.getResources().getColor(R.color.color_33633313));
        }
        // 画章节名称
        if (mChapterName == null) {
            mChapterName = "";
        }
        if (mChapterName.length() >= 18) {
            mChapterName = mChapterName.substring(0, 17) + "...";
        }
        canvas.drawText(mChapterName, 0, mChapterName.length(), mPaddingLeft, mTopArea, mTitlePaint);

        /**
         * 没有章节内容时
         */
        // 画正文的章节名称
        if (mBookContentBean == null || (1 == mBookContentBean.getUnshelf() && false == getPresenter().isChapterHasCache(mChapterIndex))) {
            if (onAdVisiableListener != null) {
                onAdVisiableListener.setOnAdHidden();
            }
            /**
             * 无网络情况
             */
            if (!NetworkUtils.isNetworkConnected(mContext) && false == getPresenter().isChapterHasCache(mChapterIndex)) {
                initNoNetwork();
                if (mNoNetworkBitmap != null) {
                    canvas.drawColor(0xFFF7F3EF);
                    // 画章节名称
                    if (mChapterName == null) {
                        mChapterName = "";
                    }
                    if (mChapterName.length() >= 18) {
                        mChapterName = mChapterName.substring(0, 17) + "...";
                    }
                    canvas.drawText(mChapterName, 0, mChapterName.length(), mPaddingLeft, mTopArea, mTitlePaint);
                    canvas.drawBitmap(mNoNetworkBitmap, 0, mNoNetworkViewY, null);
                    mReaderPresenter.dismissLoading();
                    return;
                }
            }

            if (isUnShelf && !getPresenter().isChapterHasCache(mChapterIndex)) {
                initUnShelf();
                if (unshelfBitmap != null) {
                    canvas.drawBitmap(unshelfBitmap, 0, bookViewHeight, null);
                }
                mReaderPresenter.dismissLoading();
                return;
            }
            mBigChapterLines = ReaderUtil.breakToLineList(mChapterName, mWidth - mPaddingLeft - mPaddingRight, 0, mChapterPaint);
            float y = (int) (mTopArea + (mBigChapterFM.bottom - mBigChapterFM.top)) + mLineSpace / 2;
            for (int i = 0; i < mBigChapterLines.size(); i++) {
                canvas.drawText(mBigChapterLines.get(i).getLineData(), mPaddingLeft, y, mChapterPaint);
                y += (mBigChapterFM.bottom - mBigChapterFM.top) + mLineSpace;
            }
            //画正在加载
//            String loading = "正在加载...";
//            canvas.drawText(loading, mWidth / 2 - mPaint.measureText(loading) / 2, mHeight / 2, mPaint);
//            getPresenter().showLoading(mContext.getString(R.string.loading));
            return;
        } else {
            RsLog.d("guolong" + "  mBookContentBean != null draw");
        }
        Log.i("记录", "onDraw: " + mPageIndex);
        //画电池和时间
        // 绘制电池
        if (batteryBitmapBg != null) {
            canvas.drawBitmap(batteryBitmapBg, mPaddingLeft, mHeight - mBottomArea / 2 - UIHelper.dip2px(mContext, 13), mTitlePaint);
        }
        if (batteryBitmap != null) {
            canvas.drawBitmap(batteryBitmap, mPaddingLeft + 1.75f, mHeight - mBottomArea / 2 - UIHelper.dip2px(mContext, 13) + 2.5f, mTitlePaint);
        }
        String time = dateFormat.format(new Date());
        canvas.drawText(time, mPaddingLeft + batteryBitmap.getWidth() + UIHelper.dip2px(mContext, 10), mHeight - mBottomArea / 2 - UIHelper.dip2px(mContext, 5), mTitlePaint);
        //画总百分比
//        float percent = (float) mChapterIndex * 100 / mChapterSum + (float) (mPageIndex + 1) * 100f / mPageSum / mChapterSum; //currentChapter * 100 / chapterSize;

//        String percentStr = decimalFormat.format(percent) + "%";
        String percentStr = getPresenter().getPersentValue(mChapterIndex) + "%";
        canvas.drawText(percentStr, mWidth - mPaddingRight - mTitlePaint.measureText(percentStr), mHeight - mBottomArea / 2 - UIHelper.dip2px(mContext, 5), mTitlePaint);
//        canvas.drawText(percentStr, mWidth - mPaddingRight - mTitlePaint.measureText(percentStr), mHeight - mBottomArea / 2 - fm.bottom / 2 + fm.top / 2, mTitlePaint);
        float shareTime = DateUtils.getDateMin(PreferenceUtil.getInstance(mContext).getShareTime());
        if (onAdVisiableListener != null) {
            onAdVisiableListener.setOnAdHidden();
        }
        /**
         * 如果是补贴模式，
         * 调用添加金币 ，获取总金额
         */
        if (isSubSidyState() && mBookContentBean.getContent() != null) {
            getPresenter().getChapterAddMoney(mBookContentBean.getChapterId(), getDrawBookContent(mBookContentBean.getContent() == null ? "" : mBookContentBean.getContent()).length());
        }
        /**
         * 判断是否需要绘制广告
         * 分享时间大于20分钟后需要
         * 非VIP 用户
         */
        if (advertBitmap != null) {
            Log.i(TAG, "onDraw: advertBitmap" + advertBitmap.isRecycled());
        }
        if (isShowView() && (shareTime > 20 || shareTime <= 0) && isSubSidyState()) {
            if (1 != UserInstance.getLoginData().getIsVipUser()) {
                if (advertBitmap != null && !advertBitmap.isRecycled()) {
                    canvas.drawBitmap(advertBitmap, 0, adViewY, null);
                }
                if (onAdVisiableListener != null) {
                    onAdVisiableListener.setOnAdShow();
                }
                return;
            }
        }

        if (mPageIndex == 0) {
            float y = (int) (mTopArea + (mBigChapterFM.bottom - mBigChapterFM.top)) + mLineSpace / 2;
            for (int i = 0; i < mBigChapterLines.size(); i++) {
                canvas.drawText(mBigChapterLines.get(i).getLineData(), mPaddingLeft, y, mChapterPaint);
                y += (mBigChapterFM.bottom - mBigChapterFM.top) + mLineSpace;
            }
        }

        //大标题占总高度(* 1.5是老板让把标题和正文距离拉大点)
        float chapterTitleNumHeight = mBigChapterLines.size() * (mBigChapterFM.bottom - mBigChapterFM.top + mLineSpace) * 1.5f;

        //画page在章节中的索引
//        String rightTopStr = String.valueOf((mPageIndex + 1) + "/" + mPageSum);
//        canvas.drawText(rightTopStr, mWidth - mPaddingRight - mTitlePaint.measureText(rightTopStr), mTopArea, mTitlePaint);

        mReaderPresenter.onChapterDrawed(mChapterIndex);//告诉presenter现在展示的章节索引
        //画正文
        if (mShowLines == null || mShowLines.size() <= 0)
            return;
        //char 文字索引
        mCharIndex = mShowLines.get(0).getLineFirstIndexInChapter();

        float x = 0 + mPaddingLeft;
        float y = mTopArea + mTextHeight + mLineSpace / 2;
        if (mPageIndex == 0) {
            y += chapterTitleNumHeight;
        }
        for (int i = 0; i < (mPageIndex == 0 ? mLineNumInFirstPage : mLinesNumInPage); i++) {
            //要画的这行在整章中的索引（那么在整章中前面就有 索引数 行数）
            int lineInChapter;
            if (mPageIndex == 0) {
                lineInChapter = i;
            } else {
                lineInChapter = mLinesNumInPage * (mPageIndex - 1) + mLineNumInFirstPage + i;
            }
            //如果是最后一页可能当前行数超过总行数
            if ((lineInChapter > mShowLines.size() - 1) || (lineInChapter < 0)) {
                break;
            }
            ShowLine showLine = mShowLines.get(lineInChapter);
            drawLineText(canvas, showLine, x, y);
            y += (mTextHeight + mLineSpace);
        }

        //画payBitmap
        isVipTAG = mBookContentBean.getIsVip();
        isPayTAG = mBookContentBean.getIsPay();
        if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay()) && !isSubSidyState()) {
            if (mPayBitmap == null) {
                initPayView();
            }
            des.left = mWidth / 2 - mPayBitmap.getWidth() / 2;//mPaddingLeft;
            des.top = mHeight / 7 * 3;
            des.right = (mWidth) - (mWidth / 2 - mPayBitmap.getWidth() / 2);//mWidth - mPaddingRight;
//            des.bottom = mPayView.getShowContent().getTop() + mPayView.getShowContent().getHeight();
            des.bottom = mHeight / 5 * 2 + mPayView.getShowContent().getHeight();
            canvas.drawBitmap(mPayBitmap, null, des, null);
        }
//        mReaderPresenter.dismissLoading();
    }

    /**
     * 电池
     */
    private ProgressBar batteryView;
    private Bitmap batteryBitmapBg;
    private Bitmap batteryBitmap;
    //刷新电量（低于20%，显示红色）
    private boolean isRefreshLow = false;

    //刷新电量（大于20%，显示正常颜色）
    private boolean isRefreshNor = false;
    private int battery = 40;

    public void convertBatteryBitmap() {
        batteryBitmapBg =  decodeBitmapResource(R.mipmap.kdl_icon);
        batteryView = (ProgressBar) LayoutInflater.from(mContext).inflate(R.layout.layout_battery_progress, null);
        if (battery < 20) {
            isRefreshLow = true;
            batteryView.setProgressDrawable(ContextCompat.getDrawable(mContext, R.drawable.seekbar_battery_red_bg));
        } else {
            isRefreshNor = true;
//            int theme = SettingManager.getInstance().getReadTheme();
//            if (SpUtils.getTheme(mContext)) {
            batteryView.setProgressDrawable(ContextCompat.getDrawable(mContext, R.drawable.seekbar_battery_bg));
//            } else {
//                batteryView.setProgressDrawable(ContextCompat.getDrawable(mContext, R.drawable.seekbar_day_battery_bg));
//            }
        }
        batteryView.setProgress(battery);
        batteryView.setDrawingCacheEnabled(true);
        batteryView.measure(View.MeasureSpec.makeMeasureSpec(UIHelper.dip2px(mContext, 17), View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(UIHelper.dip2px(mContext, 8), View.MeasureSpec.EXACTLY));
        batteryView.layout(0, 0, batteryView.getMeasuredWidth(), batteryView.getMeasuredHeight());
        batteryView.buildDrawingCache();
        batteryBitmap = batteryView.getDrawingCache();
    }

    public void setBattery(int battery) {
        this.battery = battery;
        //刷新电量（低于20%，显示红色）
        if (isRefreshLow) {
            if (battery >= 20) {
                isRefreshLow = false;
                batteryView = null;
            }
        }
        //刷新电量（大于20%，显示正常颜色）
        if (isRefreshNor) {
            if (battery < 20) {
                isRefreshNor = false;
                batteryView = null;
            }
        }
        if (batteryView == null) {
            if (batteryBitmap != null && !batteryBitmap.isRecycled()) {
                batteryBitmap.isRecycled();
                batteryBitmap = null;
            }
            if (batteryBitmapBg != null && !batteryBitmapBg.isRecycled()) {
                batteryBitmapBg.isRecycled();
                batteryBitmapBg = null;
            }
            convertBatteryBitmap();
        }
        batteryView.setProgress(battery);
        invalidate();
    }

    //    添加书架
    public synchronized void addCollection(BookDetailBean bookDetailBean) {
        DataSupport.getInstance().saveCollection(bookDetailBean, mBookContentBean.getChapterName()
                , mBookContentBean.getChapterId(), mChapterIndex, mPageIndex, mCharIndex);
    }

    /**
     * 保存阅读进度
     */
    public synchronized void saveHistoryAndCollection() {
        if (mBookContentBean == null) {
            return;
        }
        if (mBookCollection != null) {
            //更新书架
            DataSupport.getInstance().updateCollection(mBookCollection, mBookContentBean.getChapterName()
                    , mBookContentBean.getChapterId(), mChapterIndex, mPageIndex, mCharIndex);
        }
        if (mReaderHistory == null) {
            //加入阅读历史
            mReaderHistory = mReaderPresenter.addToHistory(mBookContentBean.getChapterName()
                    , mBookContentBean.getChapterId(), mChapterIndex, mPageIndex, mCharIndex);
        } else {
            //更新历史
            DataSupport.getInstance().updateHistory(mReaderHistory, mBookContentBean.getChapterName()
                    , mBookContentBean.getChapterId(), mChapterIndex, mPageIndex, mCharIndex);
        }
        /**
         * 保存章节缓存
         */
        getPresenter().saveCache();

//        if (!UserInstance.isLogin()) {
//            EventBus.getDefault().post(new LoadBookEvent());
//        }
        String token = UserUtil.getToken();
        if (token.isEmpty()) {
            return;
        }
        AppExecutors.getAppExecutors().networkIO().execute(() -> {
            ReadHistoryRepository historyRepository = ReadHistoryRepository.getInstance();
            if (mBookContentBean != null) {
                Call<Result> resultCall = historyRepository.uploadReadingRecord(token, mReaderPresenter.getBookId(), mBookContentBean.getChapterId());
                try {
                    Response<Result> response = resultCall.execute();
                    if (response.isSuccessful()) {
                        Log.i("HomeBookShelfFragment", "saveHistoryAndCollection: =" + mBookCollection + "isCollect:=" + getPresenter().isfromCollect() + "isJush=" + getPresenter().isfromJush());
                        if (mBookCollection != null && getPresenter().isfromCollect() && !getPresenter().isfromJush()) {
                            EventBus.getDefault().post(new LoadBookEvent(false));
                            Log.i("HomeBookShelfFragment", "saveHistoryAndCollection: 发送");
                            mBookCollection.setCategoryName("1");
                            mBookCollection.setWhetherUpdate(1);
                            mBookCollection.setCharIndex(mCharIndex);
                            int space = mChapterSum - mChapterIndex - 1;
                            if (space == 0) {
                                mBookCollection.setReadStatus("已阅至最后一章");
                                mBookCollection.setHistoryChapterName("已阅至最后一章");
                            } else if (space > 20) {
                                mBookCollection.setReadStatus(mChapterName);
                                mBookCollection.setHistoryChapterName(mChapterName);
                            } else {
                                mBookCollection.setReadStatus("剩余" + space + "章节未读");
                                mBookCollection.setHistoryChapterName("剩余" + space + "章未读");
                            }
                            mBookCollection.setChapterIndex(mChapterIndex);
                            mBookCollection.setPageIndex(mPageIndex);
                            mBookCollection.setRemove(1);
                            mBookCollection.setHistoryChapterId(mBookContentBean.getChapterId());
                            EventBus.getDefault().post(mBookCollection);
                        } else {
                            EventBus.getDefault().post(new LoadBookEvent(true));
                            Log.i("HomeBookShelfFragment", "saveHistoryAndCollection: 不发送");
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.i(TAG, "saveHistoryAndCollection: " + e.getMessage());
                }
            }
        });
    }

    private void queryHistoryAndCollection(final String bookId) {
        AppExecutors.getAppExecutors().networkIO().execute(() -> {
            BookCollection collection = LitePal.where("bookId = ?", bookId).findFirst(BookCollection.class);
            if (collection != null) {
                mBookCollection = collection;
            }
            ReaderHistory history = LitePal.where("bookId = ?", bookId).findFirst(ReaderHistory.class);
            if (history != null) {
                mReaderHistory = history;
            }
        });
    }

    /**
     * 查询历史章节，与服务器最新章节是否一至
     *
     * @param bookId
     * @return
     */
    public ReaderHistory queryChapterisNow(final String bookId) {
        ReaderHistory history = LitePal.where("bookId = ?", bookId).findFirst(ReaderHistory.class);
        return history;
    }


    /**
     * 第一页  第二页  第三页
     * 0      5       10
     * 1      6       11
     * 2      7       12
     * 3      8
     * 4      9
     *
     * @param canvas
     */
    private void drawLineText(Canvas canvas, ShowLine showLine, float x, float y) {
        canvas.drawText(showLine.getLineData(), x, y, mPaint);
        float leftPosition = x;
        float rightPosition;
        float bottomPosition = y + mPaint.getFontMetrics().descent;
        float topPosition = bottomPosition - mTextHeight - mPaint.getFontMetrics().descent;
        for (ShowChar showChar : showLine.charsData) {
            rightPosition = leftPosition + showChar.charWidth;
            RectF rectF = new RectF(leftPosition, topPosition, rightPosition, bottomPosition);
            showChar.rectF = rectF;
        }
    }

    public int prePage() {
        if (mPageIndex <= 0 && mChapterIndex == 0) {
            return BookStatus.NO_PRE_PAGE;
        }
        /**
         * 如果书籍已经下架则条下一章节
         */
        if ((isUnShelf && !getPresenter().isChapterHasCache(mChapterIndex)) || (!NetworkUtils.isNetworkConnected(mContext) && mBookContentBean == null)) {
            return preChapter(true);
        }
        if (mBookContentBean == null) {//上次就没加载成功
            return BookStatus.PRE_CHAPTER_LOAD_FAILURE;
        }

        if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay())) {
            return preChapter(true);
        }

        isPreShow = false;
        pageState = false;
        if (isSubSidyState()) {
//            adCount = PreferenceUtil.getInstance(mContext).getAdValue(getPresenter().getBookId());
            adCount = adCount - 1;
//            PreferenceUtil.getInstance(mContext).saveAdValue(getPresenter().getBookId(), adCount);
        }
        float shareTime = DateUtils.getDateMin(PreferenceUtil.getInstance(mContext).getShareTime());
        if (isShowView() && (shareTime > 20 || shareTime <= 0) && 1 != UserInstance.getLoginData().getIsVipUser() && isSubSidyState()) {
            isPreShow = true;
            return BookStatus.LOAD_SUCCESS;
        }

        if (!isNextShow) {
            if (mPageIndex > 0) {
                mPageIndex--;
            } else {
                return preChapter(true);
            }
        }
        isNextShow = false;
        return BookStatus.LOAD_SUCCESS;
    }

    public int nextPage() {
        if (mPageIndex >= mPageSum - 1 && mChapterIndex >= mChapterSum - 1) {
            return BookStatus.NO_NEXT_PAGE;
        }
        /**
         * 如果书籍已经下架则条下一章节
         * 书籍下架且无数据   或者无网络且无数据 情况下 翻章节
         */
        if ((isUnShelf && !getPresenter().isChapterHasCache(mChapterIndex)) || (!NetworkUtils.isNetworkConnected(mContext) && mBookContentBean == null)) {
            return nextChapter();
        }
        if (mBookContentBean == null) {//上次就没加载成功
            return BookStatus.NEXT_CHAPTER_LOAD_FAILURE;
        }
        /**
         * 收费章节点击跳转下一章节
         */
        if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay())) {
            return nextChapter();
        }

        isNextShow = false;
        pageState = true;
        if (isSubSidyState()) {
//            adCount = PreferenceUtil.getInstance(mContext).getAdValue(getPresenter().getBookId());
            adCount = adCount + 1;
//            PreferenceUtil.getInstance(mContext).saveAdValue(getPresenter().getBookId(), adCount);
        }
        float shareTime = DateUtils.getDateMin(PreferenceUtil.getInstance(mContext).getShareTime());
        if (isShowView() && (shareTime > 20 || shareTime <= 0) && 1 != UserInstance.getLoginData().getIsVipUser() && isSubSidyState()) {
            isNextShow = true;
            return BookStatus.LOAD_SUCCESS;
        }
        if (!isPreShow) {
            if (mPageIndex < mPageSum - 1) {
                mPageIndex++;
            } else {
                return nextChapter();
            }
        }
        isPreShow = false;
        return BookStatus.LOAD_SUCCESS;
    }

    public boolean hasNext() {
        return true;
    }

    public boolean hasPre() {
        return true;
    }

    public void recyler() {
        //释放资源
    }

    /**
     * 刷新广告页
     */
    public synchronized void refreshAd() {
        Log.i("Reader_AD", "refreshAd:刷新广告~~~");
        if (nativeTTAdView != null) {
            nativeTTAdView.loadAdView();
        }
    }

    /**
     * 是否时补贴模式
     *
     * @return true 补贴模式，false非补贴模式
     */
    public synchronized boolean isSubSidyState() {
        return 0 == PreferenceUtil.getInstance(mContext).getSubSidyStateValue() ? true : false;
    }

    public BookContentBean getCurrentContentBean() {
        return mBookContentBean;
    }

    public int getChapterIndex() {
        return mChapterIndex;
    }

//      章节缓存好了回调,告诉factory 第chapterIndex索引的章节已经缓存了
//    public void onChapterCached(int chapterIndex) {
////        Log.d(TAG, "onChapterCached! " + chapterIndex);
//        if (mChapterIndex == chapterIndex && mBookContentBean == null) {
////            Log.d(TAG, "read ChapterCached! " + chapterIndex);
//            mBookContentBean = mReaderPresenter.getChapterContent(mChapterIndex);
//            mChapterName = mBookContentBean.getChapterName();
//            mReaderPresenter.getChapterName(mChapterIndex);
//            setCanvasArea(mWidth, mHeight);
////            //需要刷新view
//            mReaderPresenter.refreshPageView();
//        }
//    }

    private boolean firstDownload = true;

    public synchronized void onChapterCached(int chapterIndex, BookContentBean bean, boolean toNewChapter) {
        if (bean == null) {
            if (mChapterIndex == chapterIndex) {
                if (!NetworkUtils.isNetworkConnected(mContext)) {
                    ToastUtil.makeShortToast("网络异常");
                } else {
                    ToastUtil.makeShortToast("数据异常，请稍后重试");
                }
            }
            Log.i(TAG, "onChapterCached: bean==null");
            if (mCharIndex == chapterIndex && bean == null) {
                startChapterFromBegin();
                mBookContentBean = null;
                mChapterName = mReaderPresenter.getChapterName(mChapterIndex);//mReaderPresenter.getChapterName(mChapterIndex);
                setCanvasArea(mWidth, mHeight);
//            //需要刷新view
                mReaderPresenter.refreshPageView();
            }
            mReaderPresenter.dismissLoading();
            return;
        }
        /**
         * 当前章节内容
         */
        if (mChapterIndex == chapterIndex) {
            if (firstDownload && !getPresenter().isChapterHasCache(chapterIndex)) {
                firstDownload = false;
                startChapterFromBegin();
            }

            mBookContentBean = bean;//mReaderPresenter.getChapterContent(mChapterIndex);
            Log.i(TAG, "onChapterCached: " + mBookContentBean.getChapterName());
            if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay()) && "2".equals(mBookContentBean.getReadType())) {
                mPageIndex = 0;
                mCharIndex = 0;
            }
            mChapterName = mReaderPresenter.getChapterName(mChapterIndex);//mReaderPresenter.getChapterName(mChapterIndex);
            setCanvasArea(mWidth, mHeight);
//            //需要刷新view
            mReaderPresenter.refreshPageView();
            mReaderPresenter.dismissLoading();
            return;
        }
        Log.i(TAG, "onChapterCached: firstDownload=" + firstDownload);
        if (firstDownload) {
            firstDownload = false;
            if (toNewChapter) {
//                mChapterIndex = chapterIndex;
                mBookContentBean = bean;//mReaderPresenter.getChapterContent(mChapterIndex);
                mChapterName = mBookContentBean.getChapterName();//mReaderPresenter.getChapterName(mChapterIndex);
                setCanvasArea(mWidth, mHeight);
//            //需要刷新view
                mReaderPresenter.refreshPageView();
                mReaderPresenter.dismissLoading();
            }
        }
        Log.i("记录", "onChapterCached: " + mPageIndex);

    }

//    /**
//     * 设置自动购买
//     *
//     * @param bean
//     */
//    public void autoBuy(BookContentBean bean) {
//        if (bean != null && "1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay())) {
//            mReaderPresenter.checkAutoBuy(UserInstance.getToken(), mReaderPresenter.getBookId(), mBookContentBean.getChapterId(), mChapterIndex, mBookContentBean.getPrice());
//        }
//    }

    public void startChapterFromBegin() {
        Log.i(TAG, "startChapterFromBegin: startChapterFromBegin");
        mPageIndex = 0;
        mCharIndex = 0;
        Log.i("记录", "startChapterFromBegin: " + mPageIndex);

    }

    /**
     * 补贴模式切换，重置页码
     */
    public void startChapterFromBegin2() {
//        if ("1".equals(isVipTAG) && "0".equals(isPayTAG)) {
//            mPageIndex = 0;
//            mCharIndex = 0;
//        }
    }

    /**
     * 跳转到下一章
     */
    public int nextChapter() {
        if (mChapterIndex >= mChapterSum - 1) {
//            ToastUtil.makeShortToast("阅读至最后一章");

            return BookStatus.NO_NEXT_CHAPTER;
        }
        mChapterIndex++;
        startChapterFromBegin();

        return toSpecifyChapter(mChapterIndex, false);
    }

    /**
     * 跳转到上一章
     */
    public int preChapter(boolean isToLastPageIndex) {
        if (mChapterIndex == 0) {
            ToastUtil.makeShortToast("阅读至第一章");
            return BookStatus.NO_PRE_CHAPTER;
        }
        mChapterIndex--;

        return toSpecifyChapter(mChapterIndex, isToLastPageIndex);
    }

    /**
     * 跳转到指定章节
     *
     * @param chapterIndex      章节索引
     * @param isToLastPageIndex 是否跳转到本章的最后一页
     * @return BookStatus       章节的加载状态
     */
    public int toSpecifyChapter(int chapterIndex, boolean isToLastPageIndex) {
//        saveHistoryAndCollection();
        //判断需要跳转的章节，如果跳转的章节比章节列表还要靠后，就返回错误
        if (chapterIndex >= mReaderPresenter.getChapterList().size() || chapterIndex < 0) {
            return -1;
        }
        // 保存当前章节索引为全局变量
        mChapterIndex = chapterIndex;
        //获取章节内容
        BookContentBean bean = mReaderPresenter.getChapterContent(mChapterIndex);
        if (bean != null || !NetworkUtils.isNetworkConnected(mContext)) {
            mBookContentBean = bean;
        }
        //通知界面章节已经改变的，做自适应的界面展示

        if (bean == null) {
            mReaderPresenter.onChapterChanged(chapterIndex);
            mChapterName = mReaderPresenter.getChapterName(mChapterIndex);
            return BookStatus.PRE_CHAPTER_LOAD_FAILURE;
        } else {
            mReaderPresenter.onChapterChanged(chapterIndex);
            mChapterName = mBookContentBean.getChapterName();//mReaderPresenter.getChapterName(mChapterIndex);
            //计算本章有多少页等等
            setCanvasArea(mWidth, mHeight);
            if (isToLastPageIndex) {
                if (!isSubSidyState()) {
                    if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay())) {
                        mPageIndex = 0;
                    } else {
                        mPageIndex = mPageSum - 1;
                    }
                } else {
                    mPageIndex = mPageSum - 1;
                }
            } else {
                mPageIndex = 0;
            }
        }
        Log.i("记录", "toSpecifyChapter: " + mPageIndex);
        return BookStatus.LOAD_SUCCESS;
    }

    public ReaderPresenter getPresenter() {
        return mReaderPresenter;
    }

    /**
     * 切换模式的时候跳转到当前章节,指定页码
     *
     * @param chapterIndex 章节索引
     * @param pageIndex    是否跳转到本章的最后一页
     * @return BookStatus
     */
    public int toSpecifyChapter(int chapterIndex, int pageIndex) {
        DLog.d(TAG, "  toSpecifyChapter chapterIndex==" + chapterIndex);
        if (chapterIndex >= mReaderPresenter.getChapterList().size() || chapterIndex < 0) {
            return -1;
        }
        mChapterIndex = chapterIndex;
        BookContentBean bean = mReaderPresenter.getChapterContent(mChapterIndex);
        mBookContentBean = bean;
        mReaderPresenter.onChapterChanged(chapterIndex);
        if (bean == null) {
            Log.i(TAG, "toSpecifyChapter: bean=null");
            mChapterName = mReaderPresenter.getChapterName(mChapterIndex);
            return BookStatus.PRE_CHAPTER_LOAD_FAILURE;
        } else {
            Log.i(TAG, "toSpecifyChapter: bean！=null");
            mChapterName = mBookContentBean.getChapterName();//mReaderPresenter.getChapterName(mChapterIndex);
            //计算本章有多少页等等
            setCanvasArea(mWidth, mHeight);
            if ("1".equals(mBookContentBean.getIsVip()) && "0".equals(mBookContentBean.getIsPay())) {
                Log.i(TAG, "toSpecifyChapter: 需要支付");
                mPageIndex = 0;
//                mCharIndex = 0;
            } else {
                Log.i(TAG, "toSpecifyChapter: 不需要支付");
                mPageIndex = pageIndex;
            }
        }
        Log.i("记录", "toSpecifyChapter: " + mPageIndex);

        return BookStatus.LOAD_SUCCESS;
    }

    public void setTextColor(int color) {
        mTextColor = color;
        init();
    }

    public void setBgColor(int color) {
        mBgColor = color;
    }

    public int getBgColor() {
        return mBgColor;
    }

    public void setSpace(int space) {
        mLineSpace = space;
        invalidate();
    }

    public void setTextSize(int size) {
        mTextSize = size;
        invalidate();
    }

    private void invalidate() {
        init();
        setCanvasArea(mWidth, mHeight);
    }

    private int payState;//付费方式

    public int getmPageIndex() {
        return mPageIndex;
    }

    public void setmPageIndex(int mPageIndex) {
        this.mPageIndex = mPageIndex;
    }

    /**
     * 章节购买
     *
     * @param isBatchPay 是否是批量购买
     */
    public void pay(boolean isBatchPay) {
        if (isBatchPay) {
            /**
             * 放开批量购买
             */
//            if (Integer.valueOf(UserInstance.getLoginData().getEnergy()) > 0) {
//                ToastUtil.makeShortToast("15天活动期间,不支持批量购买");
//            } else {
//
//            }
            payState = 2;
            mReaderPresenter.chapterBatchPay(mBookContentBean.getChapterId(), mChapterName);
        } else {
            LoginData loginData = UserInstance.getLoginData();
            if (loginData.getBlance() + loginData.getGiftBlance() + Integer.valueOf(loginData.getEnergy()) >= mBookContentBean.getPrice()) {
                /**
                 * 是否是全本购买
                 */
                if (mPayView.isAllBookPay()) {
                    //付费
                    payState = 3;
                    mReaderPresenter.allChapterPay(mBookContentBean.getChapterId(), Integer.valueOf(mBookContentBean.getVipPrice()));
                    mBookContentBean = null;
                } else {
                    //单章节购买
                    //付费
                    payState = 1;
                    mReaderPresenter.singleChapterPay(mBookContentBean.getChapterId(), mChapterIndex, Integer.valueOf(mBookContentBean.getVipPrice()), true);
                    mBookContentBean = null;
                }
            } else {
                //充值
                mReaderPresenter.recharge();
            }
        }
    }

    /**
     * 设置是否需要自动购买
     *
     * @param isAutoPay
     */
    public void selectAutoBuy(boolean isAutoPay) {
        mReaderPresenter.setCheckAutoBuy(UserInstance.getToken(), mReaderPresenter.getBookId(), isAutoPay ? "open" : "close");
    }

    /**
     * 设置是否需要关闭自动购买
     */
    public void setAutoBuy() {
        setIsAutoBuy(!isStartAuto);
        mReaderPresenter.setCheckAutoBuyStyle();
    }

    /**
     * 章节购买成功
     *
     * @param isRefresh 是否需要重新请求当前页与下一页
     */
    public void chapterPaySuccess(boolean isRefresh) {
        if (isRefresh) {
            mReaderPresenter.showLoading("正在加载...");
            mBookContentBean = null;
        }
        // 获取内容中
        mReaderPresenter.getChapterContent(mChapterIndex, payState, isRefresh);
//        setCanvasArea(mWidth, mHeight);
//        mReaderPresenter.getUserInfo(UserInstance.getToken());
    }

    public void chapterPayError(int code, String msg) {
        mReaderPresenter.dismissLoading();
        if (code != -100) {
            Toast.makeText(mPayView.getContext(), msg, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 进入阅读结束后的推荐页
     */
    public void startEndBookPage() {
        EndBookActivity.start(mContext, getPresenter().getBookId(), getPresenter().getShareUrl());
    }

    /**
     * 取消了翻页
     */
    public void cancel(boolean isCancelNextPage) {
        if (isCancelNextPage) {
            prePage();
        } else {
            nextPage();
        }
    }

    /**
     * 用于在阅读器中点击自动购买控制
     *
     * @return
     */
    public boolean getIsAutoBuy() {
        return isStartAuto;
    }

    public void setIsAutoBuy(boolean isAutoBuy) {
        isStartAuto = isAutoBuy;
    }

    /**
     * 是否支付过
     *
     * @return
     */
    public boolean isPay() {
        if (mBookContentBean != null) {
            return mBookContentBean.getIsPay() == "1" || "0".equals(mBookContentBean.getIsVip());
        }
        return false;
    }

    public void setmHeight(int mHeight) {
        this.mHeight = mHeight;
    }


    public interface OnAdVisiableListener {
        void setOnAdShow();

        void setOnAdHidden();
    }

    public OnAdVisiableListener onAdVisiableListener;

    public void setOnAdVisiableListener(OnAdVisiableListener i) {
        this.onAdVisiableListener = i;
    }


    Bitmap bmp = null;
    Canvas c = null;

    /**
     * 将布局转为btimap
     *
     * @param v
     * @param width
     * @param height
     * @param color
     * @return
     */
    public synchronized Bitmap getViewBitmap2(View v, int width, int height, int color) {
        v.layout(0, 0, width, height);
//        if (bmp != null && !bmp.isRecycled()) {
//            bmp.recycle();
//            bmp = null;
//            c = null;
//        }
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST);
        /** 当然，measure完后，并不会实际改变View的尺寸，需要调用View.layout方法去进行布局。* 按示例调用layout函数后，View的大小将会变成你想要设置成的大小。*/
        v.measure(measuredWidth, measuredHeight);
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        int w = v.getWidth();
        int h = v.getHeight();
        if (h > 0) {
            try {
                /**
                 * 无法使用RGB_565 ，有透明度；无法使用；
                 */
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                    bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_4444);
                } else {
                    bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
                }
                c = new Canvas(bmp);
                c.drawColor(color);
                /** 如果不设置canvas画布为白色，则生成透明 */
                v.layout(0, 0, w, h);
                v.draw(c);
            } catch (OutOfMemoryError outOfMemoryError) {
                outOfMemoryError.printStackTrace();
                if (bmp != null && !bmp.isRecycled()) {
                    bmp.recycle();
                    bmp = null;
                    c = null;
                }
            }

        }
        return bmp;
    }


    /**
     * 加载图片
     *   decodeResource 改用 decodeStream
     * @param id
     * @return Bitmap
     */
    private Bitmap decodeBitmapResource(int id) {
        Bitmap bitmap;
        InputStream is = mContext.getResources().openRawResource(id);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inPurgeable = true;
        opts.inInputShareable = true;
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        bitmap = BitmapFactory.decodeStream(is, null, opts);
        return bitmap;
    }

    /**
     * 释放PageFactory资源
     */
    public void recycle() {
        if (bmp != null && !bmp.isRecycled()) {
            bmp.recycle();
            bmp = null;
            c = null;
        }
        if (mNoNetworkBitmap != null && !mNoNetworkBitmap.isRecycled()) {
            mNoNetworkBitmap.recycle();
            mNoNetworkBitmap = null;
        }
        if (unshelfBitmap != null && !unshelfBitmap.isRecycled()) {
            unshelfBitmap.recycle();
            unshelfBitmap = null;
        }
        if (advertBitmap != null && !advertBitmap.isRecycled()) {
            advertBitmap.recycle();
            advertBitmap = null;
        }
        if (mBookPageBg != null && !mBookPageBg.isRecycled()) {
            mBookPageBg.recycle();
            mBookPageBg = null;
        }
        if (mPayBitmap != null && !mPayBitmap.isRecycled()) {
            mPayBitmap.recycle();
            mPayBitmap = null;
        }
        if (mNoNetworkView != null) {
            ViewParent parent = mNoNetworkView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mNoNetworkView);
            }
        }

        if (bookUnShelfView != null) {
            ViewParent parent = bookUnShelfView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(bookUnShelfView);
            }
        }

        if (nativeTTAdView != null) {
            ViewParent parent = nativeTTAdView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(nativeTTAdView);
            }
        }
        System.gc();
        Log.i(TAG, "recycle: 释放资源" + advertBitmap + unshelfBitmap + mNoNetworkView);
    }


    public boolean isRecycled() {
        if (advertBitmap != null) {
            return advertBitmap.isRecycled();
        }
        return false;
    }
}
